// import { useSyncExternalStore } from "react";
import { useSyncExternalStoreWithSelector } from "use-sync-external-store/shim/with-selector";

const createStoreImpl = (createState) => {
  let state;
  const listeners = new Set();
  const getState = () => state;
  const setState = (newState, replace) => {
    const preState = state;
    newState = typeof newState === "function" ? newState(preState) : newState;
    if (!Object.is(newState, preState)) {
      if (replace) {
        state = newState;
      } else {
        state = Object.assign({}, preState, newState);
      }
      listeners.forEach((listener) => listener(newState, preState));
    }
  };
  const subscribe = (listener) => {
    listeners.add(listener);
    return () => listeners.delete(listener);
  };
  const api = {
    subscribe,
    getState,
    setState,
  };
  state = createState(setState, getState, api);
  return api;
};

const createImpl = (createState) => {
  const api = createStoreImpl(createState);
  const useBoundStore = (selector, isEqual) =>
    useSyncExternalStoreWithSelector(
      api.subscribe,
      api.getState,
      api.getState,
      selector,
      isEqual
    );
  return Object.assign(useBoundStore, api);
};

export default createImpl;
